package br3akr.DeadlyDinnerParty.Server.Actions;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;

import br3akr.DeadlyDinnerParty.Server.Engine.Session;
import br3akr.DeadlyDinnerParty.Server.Exceptions.DeadlyDinnerPartyException;
import br3akr.DeadlyDinnerParty.Server.World.Area;
import br3akr.DeadlyDinnerParty.Server.World.GameCharacter;
import br3akr.DeadlyDinnerParty.Server.World.Item;

public class DropAction extends Action {
	boolean actionComplete;
    private ActionResponse actionResponse;
    public static final Set<String> keywords;
	static
	{
		Set<String>tempKeywords = new HashSet<String>();
		tempKeywords.add("Drop");
		tempKeywords.add("Dr");
		keywords = Collections.unmodifiableSet(tempKeywords);
	}
    
    public DropAction() {
        super("Drop", false);
    }
    
    public ActionResponse doAction(String action, Session session) throws DeadlyDinnerPartyException {
		if (action == null) {
			throw new DeadlyDinnerPartyException ("No action found.");
		}
		if (session == null) {
			throw new DeadlyDinnerPartyException ("No session found.");
		}
		
    	StringTokenizer tokenizedAction = new StringTokenizer(action);
    	String keyword = tokenizedAction.nextToken();
    	String param1 = null;
    	
		GameCharacter actor = session.getCharacter();
		
		if (actor == null) {
			throw new DeadlyDinnerPartyException ("No character found for your session.");
		}
    	
    	actionResponse = new ActionResponse();
    	actionResponse.setActingCharacter(session.getCharacter());
    	Area location = session.getCharacter().getLocation();
    	
    	Set<GameCharacter> localOnlookers = location.getAreaOnlookers(session.getCharacter(), null);
    	actionResponse.addAffectedArea(location);
    	Item it = null;
    	
		switch (keyword.toLowerCase()) {
			case "drop":
			case "dr":
		    	param1 = action.substring(keyword.length() + 1);
		    	
		    	if (param1 == null) {
		    		throw new DeadlyDinnerPartyException("What do you want to drop?");
		    	}
		    	it = actor.getInventoryItem(param1);
				actor.removeItem(it);
				if (it == null) {
					throw new DeadlyDinnerPartyException ("You're not holding anything called " + param1);
				}
				location.addItem(it);
				actionResponse.addOnlookers(localOnlookers, actor.getName() + " drops " + it.getName() + " on the ground.");
				actionResponse.setActingCharacterDescription("You drop " + it.getName() + " on the ground.");
				beginRecovery(session.getCharacter(), 3000);
				break;
			default:
				break;
		}
        
    	actionComplete = true;
        return actionResponse;
    }
	
    public ActionResponse getActionResponse() {
		return actionResponse;
	}
    
    public Set<String> getKeywords() {
        return keywords;
    }
}